require "Common/define"
require "Logic/Config"
require "Net/itemHandler"
require 'FairyGUI'


UIBag = {};
HelperFunc.SetUIEnv(UIBag)
local this = UIBag;

this.content = nil;
this.clickNormal = nil;
this.btn_equip = nil;
this.Btn_Fragment = nil;
this.btn_soul = nil

this.btn_Return = nil;
this.Btn_BGClose = nil
this.btn_Strange = nil;
this.itemTable = {};
this.itemList = {};
this.maskSize = nil;
this.ctr_page = nil

this.chips_index = nil --奇异碎片品质
this.chips_job = 0 --奇异碎片职业
this.chips_btn_frames = {}
local m_job_btns = {}
local m_call_bagType = nil

local curBagType = EnumConst.ItemTableEnum.Item;

function UIBag.Init(bagType)
    m_call_bagType = bagType
    local name, packageName = getUIName(PanelResNames.UIBag);
    panelMgr:Push(name, packageName, this.OnCreate,Config.useLocalUI);
end

--定义控件
function UIBag.OnCreate(obj)

    
    --mask = obj:GetChild("mask");
    --maskSize = mask.offsetMin;
    content = obj:GetChild("content")
    clickNormal = obj:GetChild("prop")
    clickNormal.gameObjectName = "clickNormal";
    btn_equip = obj:GetChild("equip")
    btn_stone = obj:GetChild("btn_stone")
    btn_rune = obj:GetChild("Btn_rune")
    this.Btn_Fragment = obj:GetChild("Btn_Fragment")
    btn_soul = obj:GetChild("Btn_herosoul")

    clickNormal.title = getLanguage("Sys_BagTab_Item")
    btn_equip.title = getLanguage("Sys_BagTab_Equip")
    this.Btn_Fragment.title = getLanguage("Sys_BagTab_StrangeChip")

    ctr_page = obj:GetController("page")
    btn_Return = obj:GetChild("btn_Return")
    Btn_BGClose = obj:GetChild("Btn_BGClose")
    btn_Strange = obj:GetChild("btn_Strange")

    btn_quality = obj:GetChild("btnQuality")
    ctr_sort = obj:GetController("sort")
    btn_SR = obj:GetChild("btnSR")
    btn_SSR = obj:GetChild("btnSSR")
    btn_UR = obj:GetChild("btnUR")
    btn_LR = obj:GetChild("btnLR")
    btn_LRPlus = obj:GetChild("btnLRPlus")

    -- 魂石洗炼
    this.btnBaptism = obj:GetChild("btnBaptism")
    
    this.chips_btn_frames[4] = btn_SR
    this.chips_btn_frames[6] = btn_SSR
    this.chips_btn_frames[8] = btn_UR
    this.chips_btn_frames[10] = btn_LR
    this.chips_btn_frames[16] = btn_LRPlus

    local btn = nil
    m_job_btns = {}
    for i=0, 4 do
        btn = obj:GetChild("btn" .. i)

        btn.onChanged:Add(function()
            this.OnClick_filterJob(i)
        end)
        table.insert(m_job_btns, btn)
    end

    btn_Strange.title = getLanguage("Sys_BagBtn_StrangeChip")
    ctr_page.selectedIndex = 0;
    content.itemRenderer = this.setData;
    content:SetVirtual()
    this.AddClick();
    logicMgr.HeroManager.setGetNewHeroShow(true);
    if m_call_bagType then
        curBagType = m_call_bagType
        if curBagType == EnumConst.ItemTableEnum.Fragment then
            ctr_page.selectedIndex = 3
        end
        if curBagType == EnumConst.ItemTableEnum.Soul then
            ctr_page.selectedIndex = 4
        end
    else
        curBagType = EnumConst.ItemTableEnum.Item;
    end
    
    this.refreshBag(1);
end

function UIBag.OnEnable()
    --closeUI(PanelResNames.UIHeadMenu);
    this.LocalListenEvent()
end

function UIBag.OnDisable()
    this.m_select_quality = nil
    this.chips_job = 0
    m_job_btns = nil
    --showUI(PanelNames.UIHeadMenu);
    this.LocalCloseEvent();
end

function UIBag.OnDestroy()
    this.RemoveClick();
end

--刷新界面,根据subtype显示对应界面
function UIBag.LocalListenEvent()
    ----刷新背包
    ListenEvent(Config.EventType.Fresh_Bag,this.refreshBag);
    ListenEvent(Config.EventType.Fresh_Currency,this.refreshBag);
    ListenEvent(Config.EventType.Fresh_BagUseItemBack, logicMgr.ItemManager.showGetItem);
    ListenEvent(Config.EventType.ClipUnlockPartner, logicMgr.HeroManager.ShowUnlockPartner);
    ListenEvent(Config.EventType.ClipUnlockPartner,this.refreshBag);
    ListenEvent(Config.EventType.DebrisUpdate,this.refreshBag);
    ListenEvent(Config.EventType.TimeBoxUpdate,this.refreshBag);
end

function UIBag.LocalCloseEvent()
    CloseEvent(Config.EventType.Fresh_Bag, this.refreshBag);
    CloseEvent(Config.EventType.Fresh_Currency, this.refreshBag);
    CloseEvent(Config.EventType.Fresh_BagUseItemBack, logicMgr.ItemManager.showGetItem);
    CloseEvent(Config.EventType.ClipUnlockPartner, logicMgr.HeroManager.ShowUnlockPartner);
    CloseEvent(Config.EventType.ClipUnlockPartner,this.refreshBag);
    CloseEvent(Config.EventType.DebrisUpdate,this.refreshBag);
    CloseEvent(Config.EventType.TimeBoxUpdate,this.refreshBag);

end

function UIBag.AddClick()
    btn_Return.onClick:Add(this.clickReturn)
    Btn_BGClose.onClick:Add(this.clickReturn)
    clickNormal.onClick:Add(this.LocalclickNormal)
    btn_equip.onClick:Add(this.clickEquip)
    btn_rune.onClick:Add(this.clickRune)
    btn_soul.onClick:Add(this.clickSoul)
    this.Btn_Fragment.onClick:Add(this.clickDebris)
    btn_stone.onClick:Add(this.clickHeroSoulStone)
    btn_Strange.onClick:Add(this.onClickRefinement)
    btn_quality.onClick:Add(this.OnClick_qualityArrow)
    this.btnBaptism.onClick:Add(this.onClickBaptism)

    btn_SR.onClick:Add(function()
        UIBag.OnClick_selectQuality(4)
    end)

    btn_SSR.onClick:Add(function()
        UIBag.OnClick_selectQuality(6)
    end)

    btn_UR.onClick:Add(function()
        UIBag.OnClick_selectQuality(8)
    end)

    btn_LR.onClick:Add(function()
        UIBag.OnClick_selectQuality(10)
    end)

    btn_LRPlus.onClick:Add(function()
        UIBag.OnClick_selectQuality(16)
    end)

    UIRedDots.addViewListen(PanelNames.UIBag,"UIBag"..clickNormal.gameObjectName, clickNormal, Config.RedDotsType.BagItem);
    UIRedDots.addViewListen(PanelNames.UIBag,"UIBag"..btn_stone.gameObjectName, btn_stone, Config.RedDotsType.ActivatePartner);
end

function UIBag.RemoveClick()
    btn_Return.onClick:Remove(this.clickReturn)
    Btn_BGClose.onClick:Remove(this.clickReturn)
    clickNormal.onClick:Remove(this.LocalclickNormal)
    btn_equip.onClick:Remove(this.clickEquip)
    btn_rune.onClick:Remove(this.clickRune)
    btn_stone.onClick:Remove(this.clickHeroSoulStone)
    this.Btn_Fragment.onClick:Remove(this.clickDebris)
    btn_Strange.onClick:Remove(this.onClickRefinement)
    btn_soul.onClick:Remove(this.clickSoul)
    this.btnBaptism.onClick:Remove(this.onClickBaptism)
    UIRedDots.removeViewEvent(PanelNames.UIBag)
end

function UIBag.clickReturn()
    closeUI(PanelNames.UIBag);
    logicMgr.HeroManager.setGetNewHeroShow();
end

function UIBag.LocalclickNormal()
    if curBagType ~= EnumConst.ItemTableEnum.Item then
        curBagType = EnumConst.ItemTableEnum.Item;
        this.refreshBag(1);
    end
end

function UIBag.clickEquip()
    if curBagType ~= EnumConst.ItemTableEnum.Equip then
        curBagType = EnumConst.ItemTableEnum.Equip;
        this.refreshBag(1);
    end
end

function UIBag.clickSoul()
    if curBagType ~= EnumConst.ItemTableEnum.Soul then
        curBagType = EnumConst.ItemTableEnum.Soul
        this.refreshBag(1);
    end
end

--- 点击英雄魂石页签事件
function UIBag.clickHeroSoulStone()
    if curBagType ~= EnumConst.ItemTableEnum.Hero then
        curBagType = EnumConst.ItemTableEnum.Hero;
        this.refreshBag(1);
    end
end

--奇异碎片
function UIBag.clickDebris()
    if curBagType ~= EnumConst.ItemTableEnum.Fragment then
        curBagType = EnumConst.ItemTableEnum.Fragment;
        ctr_sort.selectedIndex = 0
        this.btnBaptism.visible = this.checkBtnBaptismState()
        -- UIBag.OnClick_filterJob(0)
        this.refreshBag(1);
    end
end

--奇异碎片
function UIBag.clickRune()
    if curBagType ~= EnumConst.ItemTableEnum.Rune then
        curBagType = EnumConst.ItemTableEnum.Rune;
        -- UIBag.OnClick_filterJob(0)
        this.refreshBag(1);
    end
end

function UIBag.refreshBag(isShow)
    
    if  curBagType == EnumConst.ItemTableEnum.Item then
        itemList = logicMgr.ItemManager.getItemDataByTabType(curBagType)
        table.sort(itemList, this.normalSort)
    elseif curBagType == EnumConst.ItemTableEnum.Equip then
        itemList = logicMgr.EquipManager.getEquipList()--logicMgr.ItemManager.getItemDatabyTabType(curBagType)
        table.sort(itemList, this.equipSort)
    elseif curBagType == EnumConst.ItemTableEnum.Fragment then
        this.chips_job = this.chips_job or 0
        itemList = logicMgr.StrangeFragmentManager.FilterProfession(this.chips_job, this.m_select_quality)
        table.sort(itemList, this.debrisSort)
    elseif curBagType == EnumConst.ItemTableEnum.Hero then
        itemList = logicMgr.ItemManager.getItemDataByTabType(curBagType)
        table.sort(itemList, this.heroSort)
    elseif curBagType == EnumConst.ItemTableEnum.Soul then
        itemList = logicMgr.ItemManager.getItemDatabyItemType(curBagType)
        table.sort(itemList, this.heroSort)
    elseif curBagType == EnumConst.ItemTableEnum.Rune then
        itemList = logicMgr.RuneManager.GetStuffRuneList()
        table.sort(itemList, this.runeSort)
    end
    --if(curBagType == EnumConst.ItemTableEnum.Item) then
    --    mask.offsetMin = maskSize
    --else
    --    mask.offsetMin = maskSize + Vector2(0,111)
    --end
    content.itemRenderer = this.setData;
    content:SetVirtual()
    if isShow and isShow == 1 then
        content.numItems = 0
    end
    content.numItems = #itemList;
    if isShow and isShow == 1 then
        HelperFunc.ListTranstionPlay(content)
    end
end

--初始化物品信息
function UIBag.setData(index,obj)
    --LuaBehaviour:AddClick(go.gameObject,this.OnItemClick,itemValue);
    --LuaBehaviour:AddClick(go.gameObject.transform:Find("Select").gameObject,this.OnItemClick,itemValue);
    --item.setSelectChooseState(go.gameObject,isDecompose,false);
    --UIRedDots.removeListen( PanelNames.UIBag .. "content" .. index, Config.RedDotsType.ActivatePartner)
    obj.alpha = 1
    local item = CtrlManager.GetCtrl(PanelNames.Item);
    local data=itemList[index + 1]
    if item ~= nil then
        item.initData(obj,data,1,true);
        if curBagType == EnumConst.ItemTableEnum.Equip then
            table.insert(itemTable,obj);
            item.initData(obj,data,1,true);
        elseif curBagType == EnumConst.ItemTableEnum.Fragment then
            StrangeFragmentManager.SetItemData(obj, data, true)
        else
            item.initData(obj,data,1,true);
        end
    end
end

--[[function UIBag.hasSelectedDecompose(itemId)
    for k,v in pairs(chooseData) do
        if k == itemId then
            return true;
        end
    end
    return false;
end]]

--[[--单项点击
function UIBag.OnItemClick(obj,data)
    --显示物品详情
    if curBagType == EnumConst.ItemTableEnum.Equip then
        showUI(PanelNames.UIEquipInfo,nil,data);
        --showUI(PanelNames.UIEquipInfo,G.serverData["roleInfo"],data);
    else
        showUI(PanelNames.UIBagItemInfo,data,1);
    end
end]]

--使用礼包返回
function UIBag.getItemList()
    --奖励重复弹 已移到ItemManager.showGetItem
    --logicMgr.HeroManager.showNewHero(UIBag.showItem,TAManager.GetHeroSource.Bag);
end

function UIBag.showItem()
    local tabItems = logicMgr.ItemManager.useItemReturn();
    if table.getn(tabItems) > 0 then
        showUI(PanelNames.UICommonItemGet,nil,nil,3,tabItems)
    end
end

function UIBag.normalSort(a,b)       --> 道具：是否有红点（是->否）→ ID（从小到大）
    if a.itemModelId ~= b.itemModelId then
        return a.itemModelId < b.itemModelId
    end
    if a.bagId and b.bagId then
        return a.bagId < b.bagId
    end
    return false
end

function UIBag.equipSort(a,b)       --装备排序：装备等级（从高到低）→ 品质（从高到低）→ 部位
    if(a.quality > b.quality) then
        return true;
    elseif (a.quality == b.quality) then
        if a.part < b.part then
            return true;
        else
            return false;
        end
    else
        return false;
    end
end

function UIBag.debrisSort(a,b)
    if a.quality ~= b.quality then
        return a.quality > b.quality
    else
        if a.level ~= b.level then
            return a.level > b.level
        end
    end
    return tonumber(a.itemModelId) > tonumber(b.itemModelId)
end

function UIBag.runeSort(a,b)
    if a.quality ~= b.quality then
        return a.quality > b.quality
    else
        if a.level ~= b.level then
            return a.level > b.level
        end
    end
    return tonumber(a.itemModelId) > tonumber(b.itemModelId)
end

function UIBag.heroSort(a,b)       --> 英雄碎片：品质（从高到低）→ ID（从小到大）
    if a.quality ~= b.quality then
        return a.quality < b.quality
    end
    if a.itemModelId ~= b.itemModelId then
        return a.itemModelId < b.itemModelId
    end
    return a.bagId < b.bagId
end

--前往淬炼
function UIBag.onClickRefinement()
    UISysTips.AddMsg(getLanguage("Sys_MsgLocked"));
end

function UIBag.OnClick_qualityArrow()
    ctr_sort.selectedIndex = ctr_sort.selectedIndex == 1 and 0 or 1
end

function UIBag.OnClick_selectQuality(quality)
    -- if this.m_select_quality == quality then
    --     return
    -- end

    for k,v in pairs(chips_btn_frames) do
        if k == quality then
            v.selected = true
        else
            v.selected = false
        end
    end

    this.m_select_quality = quality
    if this.chips_job and this.chips_job ~= 0  then
        itemList = logicMgr.StrangeFragmentManager.FilterProfession(this.chips_job, quality)
    else
        itemList = logicMgr.StrangeFragmentManager.FilterQuality(quality)
    end

    table.sort(itemList, this.debrisSort)
    content.numItems = #itemList

    HelperFunc.ListTranstionPlay(content)
end

function UIBag.OnClick_filterJob(job)
    -- if this.chips_job == job then
    --     return
    -- end
    this.chips_job = job
    if job == 0 then
        for k,v in pairs(chips_btn_frames) do
            v.selected = false
        end
        this.m_select_quality = nil
    end

    for k,v in pairs(m_job_btns) do
        if k - 1 == job then
            v.selected = true
        else
            v.selected = false
        end
    end
    
    itemList = logicMgr.StrangeFragmentManager.FilterProfession(job, this.m_select_quality)
    table.sort(itemList, this.debrisSort)
    content.numItems = #itemList

    HelperFunc.ListTranstionPlay(content)
end

--- 魂石洗炼
--- @private
function this.onClickBaptism()
    showUI(PanelNames.UIDebrisBaptism)
end

--- 是否显示魂石洗炼入口
--- @private
function this.checkBtnBaptismState()
    local list = StrangeFragmentManager.FragmentInfoList
    if not list then
        return false
    end
    for k, v in pairs(list) do
        if v.quality == 10 --[[不朽--]] or v.quality == 16 --[[黯灭--]] then
            return true
        end
    end
    return false
end

return UIBag;